﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace MMS.DAL
{
    public abstract class BaseDAL
    {
        private DBHelper db = DBHelper.GetDBHelper();
        public List<T> GetListBySQL<T>(string sql)
        {
            DataTable dt = db.GetTable(sql);
            return DataTableToList<T>(dt);

        }

        private List<T> DataTableToList<T>(DataTable dt)
        {
            if (dt == null)
            {
                return null;
            }
            List<T> list = new List<T>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance<T>();

                //获取对象所有属性
                PropertyInfo[] propertyInfo = _t.GetType().GetProperties();

                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    foreach (PropertyInfo info in propertyInfo)
                    {
                        //属性名称和列名相同时赋值
                        if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
                        {
                            if (dt.Rows[i][j] != DBNull.Value)
                            {
                                string type = info.PropertyType.Name.ToLower();
                                if (type == "double")
                                {
                                    info.SetValue(_t, double.Parse(dt.Rows[i][j].ToString()), null);
                                }
                                else if (type == "int")
                                {
                                    info.SetValue(_t, int.Parse(dt.Rows[i][j].ToString()), null);
                                }
                                else
                                {
                                    info.SetValue(_t, dt.Rows[i][j], null);
                                }
                            }
                            else
                            {
                                info.SetValue(_t, null, null);
                            }

                            break;
                        }
                    }
                }
                list.Add(_t);
            }
            return list;

        }
    }
}
